package nio.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import nio.netty.service.MainService;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class NettyChatClient {

    private String ip;

    private int port;

    public NettyChatClient(String ip,int port){
        this.ip = ip;
        this.port = port;
    }
    /**
     * 初始化客户
     */
    private void init() throws Exception{
        //创建线程组
        EventLoopGroup work = new NioEventLoopGroup();
        try {
            Bootstrap boot = new Bootstrap();
            boot.group(work);
            boot.channel(NioSocketChannel.class);
            boot.handler(new ChannelInitializer<NioSocketChannel>() {

                @Override
                protected void initChannel(NioSocketChannel ch) {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast("encoder",new StringEncoder(StandardCharsets.UTF_8));
                    pipeline.addLast("decoder",new StringDecoder(Charset.forName("GBK")));
                    //pipeline.addLast(new ClientMessageHandler());

                }
            });

            ChannelFuture channelFuture = boot.connect(ip, port).sync();
            channelFuture.addListener(future -> {
                if(future.isSuccess()){
                    System.out.println("客户端启动中...");
                }
                if(future.isDone()){
                    System.out.println("客户端启动成功...OK！");
                }
            });

            System.out.println(channelFuture.channel().localAddress().toString());
            System.out.println("===============================================");
            System.out.println("#id#message 私聊用户");
            System.out.println("================================================");


            MainService service = new MainService(channelFuture);
            service.start();
            channelFuture.channel().closeFuture();
        } finally {
            work.shutdownGracefully();
        }
    }

    /**
     * 主方法入口
     * @param args 固定参数
     * @throws Exception
     */
    public static void main(String[] args) throws Exception{

        new NettyChatClient("127.0.0.1",9090).init();
    }

}
